import subprocess
import sys
import os
from datetime import datetime

def find_repo_root(path):
    current_path = path
    while current_path != os.path.dirname(current_path):
        if os.path.isdir(os.path.join(current_path, '.svn')):
            return current_path, 'svn'
        elif os.path.isdir(os.path.join(current_path, '.git')):
            return current_path, 'git'
        current_path = os.path.dirname(current_path)
    return None, None

def get_commit_logs(repo_path, start_date, end_date):
    repo_root, repo_type = find_repo_root(repo_path)
    if repo_type == 'svn':
        return get_svn_commit_logs(repo_path, start_date, end_date)
    elif repo_type == 'git':
        return get_git_commit_logs(repo_path, start_date, end_date)
    else:
        print("未识别的仓库类型", file=sys.stderr)
        return None

def get_svn_commit_logs(repo_path, start_date, end_date):
    try:
        result = subprocess.run(
            ["svn", "log", repo_path, "-r", f"{{{start_date}}}:{{{end_date}}}"],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error occurred: {e}", file=sys.stderr)
        return None

def get_git_commit_logs(repo_path, start_date, end_date):
    try:
        result = subprocess.run(
            ["git", "-C", repo_path, "log", "--since", start_date, "--until", end_date, "--pretty=format:%h - %an, %ar : %s", "--", repo_path],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error occurred: {e}", file=sys.stderr)
        return None

def main():
    repo_path = input("请输入仓库路径: ")
    start_year_month = input("请输入开始年月 (格式: YYYY-MM): ")
    end_year_month = input("请输入结束年月 (格式: YYYY-MM): ")
    output_file_path = input("请输入输出文件路径: ")

    start_date = f"{start_year_month}-01"
    end_date = f"{end_year_month}-{datetime.strptime(end_year_month, '%Y-%m').day}"

    logs = get_commit_logs(repo_path, start_date, end_date)
    if logs:
        print("提交记录如下：")
        print(logs)
        try:
            with open(output_file_path, 'w') as file:
                file.write(logs)
            print(f"提交记录已写入文件: {output_file_path}")
        except IOError as e:
            print(f"文件写入错误: {e}", file=sys.stderr)
    else:
        print("未找到提交记录或发生错误。")

if __name__ == "__main__":
    main()
